import Button from 'components/Button';
import { useUnit } from 'effector-react';
import IconCircular from 'media/icons/circular';
import { useState } from 'react';
import { sendData } from 'socketApi';
import { $hubInfo, $sensors } from 'store';
import {
  setCircularIntervalCh2,
  setCircularIntervalCh3,
} from 'store/bot';

const Controls = () => {
  const [intervalCh2, setIntervalCh2] = useState(0);
  const [intervalCh3, setIntervalCh3] = useState(0);
  const hubInfo = useUnit($hubInfo);
  const sensors = useUnit($sensors);

  const cyrcSnCh2 = () => {
    sendData([2, 1, 0, 0]);
  };

  const cyrcSnCh3 = () => {
    sendData([3, 1, 0, 0]);
  };

  const cyrcDataCh2 = () => {
    sendData([2, 0x21, 0, 0]);
  };

  const cyrcDataCh3 = () => {
    sendData([3, 0x21, 0, 0]);
  };

  const toggleIntervalCh2 = () => {
    const value = !intervalCh2 ? 1000 : 0;
    setCircularIntervalCh2(value);
    setIntervalCh2(value);
  };

  const toggleIntervalCh3 = () => {
    const value = !intervalCh3 ? 700 : 0;
    setCircularIntervalCh3(value);
    setIntervalCh3(value);
  };

  const someSeq2Empty = !sensors?.length || sensors.some(
    (sensor) => (sensor.channel2.sequenceNumber === null)
  );

  const someSeq3Empty = !sensors?.length || sensors.some(
    (sensor) => (sensor.channel3.sequenceNumber === null)
  );

  return (
    <div className="shadow px-1 py-1 my-4">
      <div className="flex gap-4 flex-row">
        <Button
          text="Цир sn ch2"
          onClick={cyrcSnCh2}
          disabled={!hubInfo}
        />
        <Button
          text="Цир sn ch3"
          disabled={!hubInfo}
          onClick={cyrcSnCh3}
          extraClass="btn-secondary"
        />

        <Button
          text="Цир Датч ch2"
          disabled={!hubInfo}
          onClick={cyrcDataCh2}
        />
        <Button
          suffixText={intervalCh2}
          disabled={someSeq2Empty}
          onClick={toggleIntervalCh2}
          children={<IconCircular />}
        />

        <Button
          text="Цир Датч ch3"
          onClick={cyrcDataCh3}
          disabled={someSeq3Empty}
          extraClass="btn-secondary"
        />
        <Button
          suffixText={intervalCh3}
          disabled={someSeq3Empty}
          onClick={toggleIntervalCh3}
          children={<IconCircular />}
          extraClass="btn-secondary"
        />
      </div>
    </div>
  );
};

export default Controls;
